package com.team9.fitness.service.impl;

import com.team9.fitness.entity.DietRecord;
import com.team9.fitness.entity.FoodInfo;
import com.team9.fitness.mapper.DietRecordMapper;
import com.team9.fitness.service.DietRecordService;
import com.team9.fitness.service.FoodInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 饮食记录服务实现类
 */
@Slf4j
@Service
public class DietRecordServiceImpl implements DietRecordService {

    @Autowired
    private DietRecordMapper dietRecordMapper;

    @Autowired
    private FoodInfoService foodInfoService;

    @Override
    public DietRecord createDietRecord(DietRecord dietRecord) {
        log.info("创建饮食记录: userId={}, foodId={}, amount={}",
                dietRecord.getUserId(), dietRecord.getFoodId(), dietRecord.getAmount());

        // 设置创建时间
        if (dietRecord.getCreatedAt() == null) {
            dietRecord.setCreatedAt(LocalDateTime.now());
        }

        // 计算营养数据
        calculateNutritionData(dietRecord);

        dietRecordMapper.insert(dietRecord);
        log.info("饮食记录创建成功: id={}", dietRecord.getId());
        return dietRecord;
    }

    /**
     * 计算营养数据
     */
    private void calculateNutritionData(DietRecord dietRecord) {
        try {
            if (dietRecord.getFoodId() != null && dietRecord.getAmount() != null) {
                // 获取食物信息
                FoodInfo foodInfo = foodInfoService.getFoodInfoById(dietRecord.getFoodId());
                if (foodInfo != null) {
                    // 设置食物名称
                    dietRecord.setFoodName(foodInfo.getName());

                    // 计算营养数据（基于每100g的营养成分）
                    double amount = dietRecord.getAmount();
                    double ratio = amount / 100.0; // 转换为100g的比例

                    // 计算总热量
                    if (foodInfo.getCalories() != null) {
                        dietRecord.setTotalCalories(Math.round(foodInfo.getCalories() * ratio * 100.0) / 100.0);
                    }

                    // 计算总碳水化合物
                    if (foodInfo.getCarbohydrates() != null) {
                        dietRecord
                                .setTotalCarbohydrates(Math.round(foodInfo.getCarbohydrates() * ratio * 100.0) / 100.0);
                    }

                    // 计算总蛋白质
                    if (foodInfo.getProtein() != null) {
                        dietRecord.setTotalProtein(Math.round(foodInfo.getProtein() * ratio * 100.0) / 100.0);
                    }

                    // 计算总脂肪
                    if (foodInfo.getFat() != null) {
                        dietRecord.setTotalFat(Math.round(foodInfo.getFat() * ratio * 100.0) / 100.0);
                    }

                    log.info("营养数据计算完成: 热量={}, 碳水={}, 蛋白={}, 脂肪={}",
                            dietRecord.getTotalCalories(), dietRecord.getTotalCarbohydrates(),
                            dietRecord.getTotalProtein(), dietRecord.getTotalFat());
                } else {
                    log.warn("食物信息不存在: foodId={}", dietRecord.getFoodId());
                }
            } else {
                log.warn("食物ID或食用量为空，无法计算营养数据");
            }
        } catch (Exception e) {
            log.error("计算营养数据失败", e);
        }
    }

    @Override
    public List<DietRecord> getDietRecordsByUserAndDate(Long userId, String date) {
        log.info("获取用户{}在{}的饮食记录", userId, date);

        // 解析日期字符串为LocalDate
        LocalDate targetDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        // 查询指定日期的记录（通过比较日期部分）
        List<DietRecord> records = dietRecordMapper.selectByUserIdAndDate(userId, targetDate);

        log.info("找到{}条饮食记录", records.size());
        return records;
    }

    @Override
    public Map<String, Object> getNutritionSummaryByUserAndDate(Long userId, String date) {
        log.info("获取用户{}在{}的营养汇总", userId, date);

        // 解析日期字符串为LocalDate
        LocalDate targetDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        // 查询指定日期的记录
        List<DietRecord> records = dietRecordMapper.selectByUserIdAndDate(userId, targetDate);

        // 计算营养汇总
        double totalCalories = 0.0;
        double totalCarbohydrates = 0.0;
        double totalProtein = 0.0;
        double totalFat = 0.0;

        for (DietRecord record : records) {
            if (record.getTotalCalories() != null) {
                totalCalories += record.getTotalCalories();
            }
            if (record.getTotalCarbohydrates() != null) {
                totalCarbohydrates += record.getTotalCarbohydrates();
            }
            if (record.getTotalProtein() != null) {
                totalProtein += record.getTotalProtein();
            }
            if (record.getTotalFat() != null) {
                totalFat += record.getTotalFat();
            }
        }

        Map<String, Object> summary = new HashMap<>();
        summary.put("totalCalories", Math.round(totalCalories * 100.0) / 100.0);
        summary.put("totalCarbohydrates", Math.round(totalCarbohydrates * 100.0) / 100.0);
        summary.put("totalProtein", Math.round(totalProtein * 100.0) / 100.0);
        summary.put("totalFat", Math.round(totalFat * 100.0) / 100.0);
        summary.put("recordCount", records.size());
        summary.put("date", date);

        log.info("营养汇总计算完成: 热量={}, 碳水={}, 蛋白={}, 脂肪={}",
                totalCalories, totalCarbohydrates, totalProtein, totalFat);

        return summary;
    }

    @Override
    public List<DietRecord> getDietRecordsByUser(Long userId) {
        log.info("获取用户{}的所有饮食记录", userId);
        return dietRecordMapper.selectByUserId(userId);
    }

    @Override
    public void deleteDietRecord(Long id) {
        log.info("删除饮食记录: id={}", id);
        dietRecordMapper.deleteById(id);
        log.info("饮食记录删除成功: id={}", id);
    }
}
